import axios from "axios";

import Router from "../router/index.js";

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  timeout: 30000, // request timeout
});

service.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem("manpu_token");
    if (token) {
      config.headers["Authorization"] = "bearer " + token;
    }

    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const { status, data, message } = response;

    if (data) {
      if (data.code >= 200 && data.code < 300) {
        return data.data;
      } else if (data.code == 401) {
        ElMessage.error(data.msg);
        Router.push("/login");
        return Promise.reject(new Error(data.msg));
      } else {
        let str;
        if (data.msg) {
          if (typeof data.msg !== "string") {
            str = data.msg.toString();
          } else {
            str = data.msg;
          }
        } else {
          return data;
        }

        ElMessage.error(str);
        return Promise.reject(new Error(data.msg));
      }
    } else {
      ElMessage.error("请求错误！");
      return Promise.reject(new Error("请求错误！"));
    }
  },
  (error) => {
    const { statusText, status } = error.response;
    const { message, data } = error.response.data;

    // Router.push("/login");
    ElMessage.error(message || statusText || "请求错误！");
    return Promise.reject(new Error(message || statusText));
  }
);

export default service;
